import axios from 'axios'
import router from '@/router'
import { useUserStore } from '@/stores/userStore'
//页面弹框提示引入ElMessage，element-plus/theme-chalk/el-message.css
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'

// 创建axios实例
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// axios请求拦截器,统一在请求头里面添加token
httpInstance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    //拼接后端需要的token
    const token = userStore.userInfo.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (e) => Promise.reject(e)
)

// axios响应式拦截器
httpInstance.interceptors.response.use(
  (res) => res.data,
  (e) => {
    //统一对接口返回的错误提示做拦截
    ElMessage({
      type: 'warning',
      message: e.response.data.message
    })

    //401token失效判断
    //清除本地用户数据，跳转登录页
    console.log('zhuangtai',e.response.status)
    if (e.response.status === 401) {
      const userStore = useUserStore()
      userStore.cleanUserInfo()
      router.push('/login')
    }

    return Promise.reject(e)
  }
)

export default httpInstance
